package com.maben.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;
import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.beans.PropertyDescriptor;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 导出excel设置引擎
 */
public class ExcelExportEngineUtil {


    /**
     * 写入excel
     */
    public static void write2Excel(Object obj, Workbook workbook) throws Exception {
        write2Excel(obj, workbook, null);
    }

    /**
     * 写入excel
     */
    public static void write2Excel(Object obj, Workbook workbook, String imagePath) throws Exception {
        final Class<?> clazz = obj.getClass();
        final Field[] declaredFields = clazz.getDeclaredFields();
        final Sheet sheet = workbook.getSheetAt(0);
        final int lastRowNum = sheet.getLastRowNum();
        for (int i = 0; i <= lastRowNum; i++) {
            final Row row = sheet.getRow(i);
            if (row == null) {
                continue;
            }
            final short lastCellNum = row.getLastCellNum();
            for (int j = 0; j < lastCellNum; j++) {
                final Cell cell = row.getCell(j);
                if (cell == null) {
                    continue;
                }
                final CellType cellType = cell.getCellType();
                if (cellType.equals(CellType.FORMULA)) {
                    //公式先不处理
                    continue;
                }
                String stringCellValue = cell.getStringCellValue();
                if (StringUtils.isNotBlank(stringCellValue)) {
                    stringCellValue = stringCellValue.trim().replace(" ", "");
                    if (stringCellValue.startsWith("{{") && stringCellValue.endsWith("}}")) {
                        final String key = stringCellValue.replace("{{", "").replace("}}", "");
                        for (Field field : declaredFields) {
                            final String name = field.getName();
                            if (StringUtils.equals(name, key)) {
                                final PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, clazz);
                                final Method readMethod = propertyDescriptor.getReadMethod();
                                final Object value = readMethod.invoke(obj);
                                if (value instanceof Date) {
                                    cell.setCellValue(new DateTime(value).toString("yyyy-MM-dd"));
                                } else {
                                    cell.setCellValue(value.toString());
                                }
                                break;
                            }
                        }
                    }
                }
            }
        }
        if (StringUtils.isNotBlank(imagePath)) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ClassPathResource classPathResourcePhoto = new ClassPathResource(imagePath);
            BufferedImage bufferedImage = ImageIO.read(classPathResourcePhoto.getInputStream());
            ImageIO.write(bufferedImage, "JPG", byteArrayOutputStream);
            final Sheet sheetConfig = workbook.getSheetAt(1);
            final XSSFClientAnchor anchor = new XSSFClientAnchor(
                    36000,//左边向x轴偏移多少（单位：1厘米=36000）
                    36000,//上边向y轴偏移多少
                    0, //右边向x轴偏移多少
                    0, //下边向y轴偏移多少
                    ((Double) sheetConfig.getRow(1).getCell(1).getNumericCellValue()).intValue(), //开始列
                    ((Double) sheetConfig.getRow(2).getCell(1).getNumericCellValue()).intValue(), //开始行
                    ((Double) sheetConfig.getRow(3).getCell(1).getNumericCellValue()).intValue() + 1, //结束列(为了使图片沾满整个，需要+1)
                    ((Double) sheetConfig.getRow(4).getCell(1).getNumericCellValue()).intValue() + 1 //结束行(为了使图片沾满整个，需要+1)
            );
            final Drawing<?> drawingPatriarch = sheet.createDrawingPatriarch();//控制图片的写入
            drawingPatriarch.createPicture(anchor, workbook.addPicture(byteArrayOutputStream.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
        }
        //将配置sheet表删除
        workbook.removeSheetAt(1);
    }
}
